﻿using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Text;

namespace WindStyle.WindowsLiveWriter.Plugin.ExifInfo
{
    public partial class OptionForm : Form
    {
        private string field_demoImagePath;
        public OptionForm()
        {
            InitializeComponent();
            this.GenerateDemoImage();
            this.BindControls();
        }

        /// <summary>
        /// Save a demo image to ApplicationData folder for template preview.
        /// </summary>
        private void GenerateDemoImage()
        {
            this.field_demoImagePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                @"WindStyle\ExifInfo\Demo.jpg");
            if (!File.Exists(field_demoImagePath))
            {
                string demoImgDir = Path.GetDirectoryName(field_demoImagePath);
                if (!Directory.Exists(demoImgDir))
                    Directory.CreateDirectory(demoImgDir);
                using (Stream stream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("WindStyle.WindowsLiveWriter.Plugin.ExifInfo.Resources.Demo.jpg"))
                {
                    using (FileStream fs = new FileStream(field_demoImagePath, FileMode.Create))
                    {
                        byte[] bytesInStream = new byte[stream.Length];
                        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
                        fs.Write(bytesInStream, 0, bytesInStream.Length);
                        fs.Flush();
                    }
                }
            }
        }

        private void BindControls()
        {
            foreach (Template template in Option.CurrentSettings.Templates)
            {
                this.lb_templates.Items.Add(template);
                this.cb_defaultTemplate.Items.Add(template.Name);
            }
            if (this.lb_templates.Items.Count > 0)
                this.lb_templates.SelectedIndex = 0;
            if (!string.IsNullOrEmpty(Option.CurrentSettings.DefaultTemplateName))
                this.cb_defaultTemplate.Text = Option.CurrentSettings.DefaultTemplateName;
            this.btn_removeTemplates.Enabled = this.lb_templates.Items.Count > 1;
        }

        [Obsolete("How to get current blog id?")]
        private void RefreshPreview()
        {
            if (this.lb_templates.SelectedIndex < 0)
                return;
            Template template = (this.lb_templates.SelectedItem as Template);
            string html = APIHelper.GetEditorTemplateHtml();
            html = html.Replace("{post-title}", template.Name);

            Size size = Utilities.GetDefaultImageSize(APIHelper.DefaultBlogId, this.field_demoImagePath);
            html = html.Replace("{post-body}", Utilities.GetExifInfoString(this.field_demoImagePath,
                template.HtmlTemplate, size));


            this.wb_template.DocumentText = html;
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            Option.Save();
        }

        private void btn_Default_Click(object sender, EventArgs e)
        {
            Option.CurrentSettings.Reset();
            this.BindControls();
        }

        private void lb_templates_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.RefreshPreview();
        }

        private void btn_addTemplates_Click(object sender, EventArgs e)
        {
            using (TemplateEditor editor = new TemplateEditor())
            {
                if (editor.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Option.CurrentSettings.Templates.Add(editor.HtmlTemplate);
                    this.lb_templates.Items.Add(editor.HtmlTemplate);
                    this.cb_defaultTemplate.Items.Add(editor.HtmlTemplate);
                    this.btn_removeTemplates.Enabled = this.lb_templates.Items.Count > 1;
                }
            }
        }

        private void btn_editTemplates_Click(object sender, EventArgs e)
        {
            if (this.lb_templates.SelectedIndex < 0)
                return;
            Template selected = this.lb_templates.SelectedItem as Template;
            using (TemplateEditor editor = new TemplateEditor(selected))
            {
                if (editor.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Option.CurrentSettings.Templates.Insert(Option.CurrentSettings.Templates.IndexOf(selected), editor.HtmlTemplate);
                    Option.CurrentSettings.Templates.Remove(selected);
                    this.lb_templates.Items.Insert(this.lb_templates.SelectedIndex, editor.HtmlTemplate);
                    this.lb_templates.Items.Remove(this.lb_templates.SelectedItem);
                    this.lb_templates.SelectedItem = editor.HtmlTemplate;
                    this.cb_defaultTemplate.Items.Insert(this.lb_templates.SelectedIndex, editor.HtmlTemplate);
                    this.cb_defaultTemplate.Items.Remove(this.lb_templates.SelectedItem);
                    this.RefreshPreview();
                }
            }
        }

        private void btn_removeTemplates_Click(object sender, EventArgs e)
        {
            if (this.lb_templates.SelectedIndex < 0 || this.lb_templates.Items.Count == 1)
                return;
            Template selected = this.lb_templates.SelectedItem as Template;
            Option.CurrentSettings.Templates.Remove(selected);
            this.lb_templates.Items.Remove(selected);
            this.cb_defaultTemplate.Items.Remove(selected);
            if (this.cb_defaultTemplate.SelectedIndex == -1)
                this.cb_defaultTemplate.SelectedIndex = 0;
            this.lb_templates.SelectedIndex = 0;
            this.btn_removeTemplates.Enabled = this.lb_templates.Items.Count > 1;
            this.RefreshPreview();
        }

        private void OptionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                Option.Rollback();
            }
        }

        private void cb_defaultTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            Option.CurrentSettings.DefaultTemplateName = this.cb_defaultTemplate.Text;
        }
    }
}
